<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import DialogCategory from './DialogCategory.vue'
import AddName from './AddName.vue'
import CategorySort from './CategorySort.vue'
import { useDistInfoStore } from '@/stores/dict.js';
import Sortable from 'sortablejs' 
import {diagnosticList,addOrEditDialog,deleteSetting,diagSort } from '@/api/ShopDatabase/goodsSetting.js'
import SlotTable from './SlotTable.vue'
import {tranListToTreeData} from '@/hooks/index.js' 
const distInfoStore = useDistInfoStore();
const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();


// dialog弹框组件

// 弹框文字
const dialogTitle = ref('')
const handleClose = () => {
    cancel()
}

// 诊断类别弹框
const options = computed(()=>{
    return distInfoStore.getDistInfo("经营品牌").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})


onMounted(() => {

})




// 新增诊断类别
const dialogDiaCategory = ref(false)

const backForm = ref({
     diagnosisValue:'', //诊断类别
     permissionId:'', //经营品牌id
     id:''
})


const changeDiaCategory = (val) => {
  backForm.value = {
        diagnosisValue:'', //诊断类别
        permissionId:'', //经营品牌id
        id:''
    }
    console.log(val,'dialogval');
    dialogDiaCategory.value = false
    val == 'refresh' ? seachTable.value.handlerSearch() : ''
}

// 新增诊断名称
const dialogAddName = ref(false)
const addBackName = ref({
  diagnosisValue:'',
  parentId:'',
  id:''
})

// 编辑诊断名称
const handleEdit = (index,row) => {
  addBackName.value = {
          permissionId:row.permissionId,
          diagnosisValue: row.diagnosisValue,
          parentId:row.parentId,
          id:row.id
      }
  dialogAddName.value = true
  dialogTitle.value = '编辑诊断名称'
 

}


// 删除诊断名称
const handleDelete = (row) => {
  console.log(row,'row');
  ElMessageBox(
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error',
                title: '提示',
                showCancelButton: true,
                confirmButtonClass: 'el-button--danger',
                message: row.parentId == 0 ? "删除该类别时，将同步删除该类别下的诊断名称。确认删除吗？" : '确认删除该诊断名称吗？',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonLoading = true
                        instance.confirmButtonText = 'Loading...'
                        try {
                          let data = {
                            id:row.id
                          }
                          const res = await deleteSetting(data)
                          ElMessage.success('删除成功');
                          
                        } catch (error) {
                          
                        }finally{ 
                          seachTable.value.handlerSearch();
                          instance.confirmButtonLoading = false
                          done()
                        }
                      
                    } else {
                        done()
                    }
                },
            }
        )
}

const changeAddname = (val) => {
  if(val == 'clear'){
    seachTable.value.handlerSearch();
  }else{
    dialogAddName.value = val
  }
   
}

// 诊断类别排序
const dialogCategorySort = ref(false)
const changeCategorySort = (val) => {
     
    dialogCategorySort.value = val
}

// 确认弹框
const submitCategorySort = async(val) => {
  try {
    changeCategorySort(false)
    tableLoading.value = true;
    let data = {
      sortVoList:val
    }
  const res = await diagSort(data)
  seachTable.value.handlerSearch()
  instance.proxy.$forceUpdate()
  ElMessage({
    type:'success',
    message: '操作成功',
  });
  } catch (error) {
    
  }finally{
    tableLoading.value = false;
  }
 
}

// 表格控件
const formInline = ref([
   
])

const btnLefts = ref([ 
    {
        label:"诊断类别",
        plain:false,
        type:"primary",
        show:true,
        img:new URL("@/assets/icon/add-goods.png",import.meta.url),
        click:async ()=>{
            dialogDiaCategory.value = true
            dialogTitle.value = '新增诊断类别'
        }
    },
    {
        label:"类别排序",
        plain:true,
        type:"primary",
        show:true,
        img:new URL("@/assets/icon/sort.png",import.meta.url),
        click:async ()=>{
            // router.push({name:"merchantChildManageAdd"})
            dialogTitle.value = '诊断类别排序'
            dialogCategorySort.value = true

        }
    },

])
const btnRights = ref([
    // {
    //     label:"导出",
    //     plain:false,
    //     plain:true,
    //     show:true,
    //     img:new URL("@/assets/icon/btn-export.png",import.meta.url),
    //     style:"border-color:#0C268C;color:#0C268C",
    //     click:async ()=>{

    //     }
    // }
])

const tableConfig = ref([
    {
      prop: "permissionId",
      label: "经营品牌",
      format: (val) => {
        let newArray = val.split(',')
        let matches = []
        for (const valueToMatch of newArray) {
            const matchingItem = options.value.find(item => item.value === valueToMatch);
            if (matchingItem) { 
                matches.push(matchingItem.label);
            }
          }
          return matches.join("、");
      }
    },
    {
      prop: "name",
      type:"expand",
      slotExpandName:'diagExpand',
      width: 40,
    },
    {
      prop: "diagnosisValue",
      label: "诊断类别",
      width: 300,
    },
    {
      prop: "mobile",
      label: "诊断名称",
  
    },
    {
      type: "action",
      label: "操作",
      width: 300,
      btns: [
        {
          label: () => "新增诊断名称",
          type:"primary",
          show:(row)=>{
            return true;
          },
          click: async (row) => {
            console.log(row,'row');
            addBackName.value = {
                 permissionId:row.permissionId,
                 diagnosisValue:'',
                 parentId:row.id,
                 id:''
              }
            dialogAddName.value = true
            dialogTitle.value = '新增诊断名称'
          },
        },
        {
          label: () => "编辑",
          type:"success",
          show:(row)=>{
            return true;
          },
          click: async (row) => {
           
                console.log('编辑了');
                backForm.value = {
                  parentId:row.parentId,
                  id:row.id,
                  diagnosisValue:row.diagnosisValue, //诊断类别
                  permissionId:row.permissionId.split(','), //经营品牌id
                }

                dialogDiaCategory.value = true
                dialogTitle.value = '编辑诊断类别'
            
          },
        },
        {
          label: () => "删除",
          type:"danger",
          show:(row)=>{
            return true;
          },
          click: async (row) => {
            handleDelete(row)
          },
        }
      ],  
    },
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableDatas = ref([]);
const tableData = ref([])

const expandRowKeys = ref(['']);
const expandChanges = (row) => {
  if (row.id === expandRowKeys.value[0]) {
    expandRowKeys.value[0] = '';
  } else {
    expandRowKeys.value[0] = row.id;
  }
};
watch(tableDatas,()=>{
  if(tableDatas.value.length > 0 && expandRowKeys.value[0] === ''){
    expandRowKeys.value[0] = tableDatas.value[0].id;
  }
})


const handlerSearch = async (formInline)=>{
  console.log(formInline,'llllll');
    tableLoading.value = true;
    try{
        const res = await diagnosticList()
        tableData.value = res
        const data = tranListToTreeData(res,0)
        console.log(data,'data');
        totalPage.value = 100;
        tableDatas.value = data;
        tableLoading.value = false;
    }catch(e){
        // tableLoading.value = false;
    }finally{
        tableLoading.value = false;
    }
}



</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading" 
          :tableConfig="tableConfig"
          :tableData="tableDatas" 
          :totalPage="totalPage" 
          :isShowPage="false"
          @handlerSearch="handlerSearch"
          @expandChange="expandChanges"
          :isDrag="true"
          row-key="id"
          :nativeAttribute="{}"
        >
            <template #diagExpand="{row,index}">
               <div class="diag-expand">
                <SlotTable 
                :tableDataChild="row.children"
                @handleEdit="handleEdit"
                @handleDelete="handleDelete"
                @sortSubmit="submitCategorySort"
                ></SlotTable> 
               </div>
            </template>
        </SeachTable>
       <dialog-category 
        v-if="dialogDiaCategory"
       :dialogTitle="dialogTitle"
        :dialogDiaCategory="dialogDiaCategory"
        :backForm="backForm"
        @changeDiaCategory="changeDiaCategory"
        :options="options"
       ></dialog-category>
       <add-name
        v-if="dialogAddName"
       :dialogTitle="dialogTitle"
        :dialogAddName="dialogAddName"
        @changeAddname="changeAddname"
        :backForm="addBackName"
       ></add-name>
       <category-sort
       v-if="dialogCategorySort"
       :dialogTitle="dialogTitle"
       :dialogCategorySort="dialogCategorySort"
       @changeCategorySort="changeCategorySort"
       @submitCategory="submitCategorySort"
       :tableData="tableData"
       >
       </category-sort>
        </div>
    </template>

<style lang="less" scoped>
   :deep(.line-block){
        display: none !important;
   }
   :deep(.btnTip){
    //  margin-right: 12px !important;
    width: 8px !important;
   }
   .diag-expand{
        
    :deep(.el-table__cell){
        background: none !important;
   }
 
   
   }
   :deep(.btn-area){
      padding:0px !important;
    }
  
</style>

<style lang="less" >
   .event-row {
        background-color: #F9F9F9 !important;
    }
    .odd-row{
        background-color: #fff !important;
    }
</style>